package com.dingreading.cloud.subject.service.impl;

import com.dingreading.cloud.subject.dto.CourseTrainTypesDto;
import com.dingreading.cloud.subject.entity.CourseTrainTypes;
import com.dingreading.cloud.subject.entity.table.CourseTrainTypesTableDef;
import com.dingreading.cloud.subject.mapper.CourseTrainTypesMapper;
import com.dingreading.cloud.subject.service.CourseTrainTypesService;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 叮叮线下培训分类表 服务层实现。
 *
 * @author EDY
 * @since 2025-11-18
 */
@Service
public class CourseTrainTypesServiceImpl extends BaseServiceImpl<CourseTrainTypesMapper, CourseTrainTypes, CourseTrainTypesTableDef> implements CourseTrainTypesService {

    @Override
    protected CourseTrainTypesTableDef getTable() {
        return CourseTrainTypesTableDef.courseTrainTypes;
    }

    @Override
    public List<CourseTrainTypesDto> getMainType() {
        QueryWrapper wrapper = QueryWrapper.create()
                .where(table.parentId.eq(0L))
                .orderBy(table.showOrder.asc());
        return getMapper().selectListByQueryAs(wrapper, CourseTrainTypesDto.class);
    }

    @Override
    public Map<Long, List<CourseTrainTypesDto>> getByMainIds(List<Long> mainIds) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.parentId.ne(0L))
                .and(table.mainId.in(mainIds))
                .and(table.enabled.eq(1));

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.levelIndex.asc(), table.showOrder.asc());

        RelationManager.addIgnoreRelations("fileList", "typeList");
        List<CourseTrainTypesDto> courseTrainTypesDtos = getMapper().selectListWithRelationsByQueryAs(wrapper, CourseTrainTypesDto.class);
        Map<Long, List<CourseTrainTypesDto>> typesDtoMap = courseTrainTypesDtos.stream().collect(Collectors.groupingBy(CourseTrainTypesDto::getMainId));
        return typesDtoMap;
    }

    @Override
    public CourseTrainTypes getByUid(String typUid) {
        return getMapper().selectOneByCondition(table.uid.eq(typUid));
    }
}
